package pixel

import (
	"alex/sensorfingerprint/data"
	"fmt"
	"image"
	"image/color"
	"math"
)

// loop which detects the surrounding pixels
func DetectSurroundingPixels(img image.Image, pixel [][]data.PixelData) {
	fmt.Printf("=")
	for width := img.Bounds().Min.X; width < img.Bounds().Max.X; width++ {
		for height := img.Bounds().Min.Y; height < img.Bounds().Max.Y; height++ {
			diff, count := 0.0, 0.0
			startX, startY := img.Bounds().Min.X, img.Bounds().Min.Y
			endX, endY := img.Bounds().Max.X - 1, img.Bounds().Max.Y - 1
			myColour := img.At(width, height).(color.RGBA)

			// borders are recognized here
			if left := width - 1; left >= startX {
				startX = left
			}
			if top := height - 1; top >= startY {
				startY = top
			}
			if right := width + 1; right <= endX {
				endX = right
			}
			if bottom := height + 1; bottom <= endY {
				endY = bottom
			}
			// neighbouring pixels are compared...
			for i := startX; i <= endX; i++ {
				for j := startY; j <= endY; j++ {
					if width != i || height != j {
						tmpColour := img.At(i, j).(color.RGBA)
						diff += pixelCompare(myColour, tmpColour)
						count++
					}

				}
			}
			// ... and averaged
			diff /= count
			checkMap(myColour, pixel, diff, width, height)
		}
	}
}

func CompareImageWithFingerprint(img image.Image, pixel [][]data.PixelData, threshold int) (float64, float64) {
	countMask, countImg := 0.0, 0.0
	for i := range pixel {
		for j := range pixel {
			if pixel[i][j].Count > threshold {
				countMask++
				if pixel[i][j].Image.R == img.At(i, j).(color.RGBA).R &&
					pixel[i][j].Image.G == img.At(i, j).(color.RGBA).G &&
					pixel[i][j].Image.B == img.At(i, j).(color.RGBA).B {
					countImg++
				}
			}
		}
	}
	return countMask, countImg
}

// different RGA values are detected
// gray = 0.299 * red + 0.578 * green + 0.114 * blue
func pixelCompare(myColour, tmpColour color.RGBA) float64 {
	tmp := math.Abs(float64(myColour.R) - float64(tmpColour.R))
	//tmp += math.Abs(float64(myColour.G - tmpColour.G))
	//tmp += math.Abs(float64(myColour.B - tmpColour.B))
	return tmp
}

func checkMap(myColour color.RGBA, pixel [][]data.PixelData, diff float64, width int, height int) {
	if diff > 18 {
		//TODO: threshold setzn, zB diff>>2 oder diff>>3
		if pixel[width][height].Count == 0 {
			addMap(myColour, pixel, width, height)
		} else {
			mergeMap(myColour, pixel, width, height)
		}
	}
}

func addMap(myColour color.RGBA, pixel [][]data.PixelData, width int, height int) {
	//fmt.Println("entering")
	pixel[width][height].Image = myColour
	pixel[width][height].Count = 1
}

func mergeMap(myColour color.RGBA, pixel [][]data.PixelData, width int, height int) {
	if myColour.R == pixel[width][height].Image.R &&
		myColour.G == pixel[width][height].Image.G &&
		myColour.B == pixel[width][height].Image.B {
		pixel[width][height].Count++
	}
}
